package icu.groot.alan.hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.GsonBuilder;
import icu.groot.alan.hotel.entity.dao.AccountDo;
import icu.groot.alan.hotel.entity.dto.LoginUserDto;
import icu.groot.alan.hotel.entity.req.AccountLoginRo;
import icu.groot.alan.hotel.entity.vo.LoginUserVo;
import icu.groot.alan.hotel.mapper.AccountMapper;
import icu.groot.alan.hotel.service.AccountService;
import icu.groot.alan.hotel.util.BizException;
import icu.groot.alan.hotel.util.GrootApi;
import icu.groot.alan.hotel.util.LoginTokenEntity;
import icu.groot.alan.hotel.util.ResultCodeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDo> implements AccountService {
    @Resource
    AccountMapper accountMapper;

    /**
     * 用户登录
     */
    @Override
    public LoginUserDto login(AccountLoginRo loginRo) {
        AccountDo accountDo = accountMapper.selectOne(new QueryWrapper<AccountDo>().eq("acc_phone", loginRo.getAccPhone()));
        if (accountDo == null){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("登录失败,用户不存在"));
        }
        if (!loginRo.getAccPassword().equals(accountDo.getAccPassword())){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("登录失败, 密码错误"));
        }

        LoginTokenEntity loginTokenEntity = new LoginTokenEntity();

        GrootApi.BeanCopy.copyProperties(accountDo, loginTokenEntity);

        LoginUserDto loginUserDto = new LoginUserDto();
        GrootApi.BeanCopy.copyProperties(loginTokenEntity, loginUserDto);
        loginUserDto.setToken(GrootApi.Jwt.create(new GsonBuilder().create().toJson(loginTokenEntity)));

        return loginUserDto;
    }
}
